package com.alg.local.gateway.util;

import com.alg.local.gateway.config.GatewayConstant;
import com.alg.local.gateway.entity.EncrProps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author al
 * @date 2023/12/15 11:23
 * @description
 */
@Component
@Slf4j
public class GatewayUtil {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    EncrProps encrProps;

    public Map<String, String> getClientAesKey(ServerHttpRequest request) {
        Map<String, String> result = new HashMap<>();

        String key;
        String iv;

        String clientId = request.getHeaders().getFirst(GatewayConstant.SYS_FLAG);
        if (StringUtils.isEmpty(clientId)) {
            log.info("clientId is null, set default config");
            key = encrProps.getAesKey();
            iv = encrProps.getAesIv();
        } else {
            log.info("clientId exits, set client config");
            Map<String, String> simpleMapTest = redissonClient.getMap(GatewayConstant.RSA_KEY_MAP, new StringCodec());
            key = simpleMapTest.get("key:" + clientId);
            iv = simpleMapTest.get("iv:" + clientId);
        }

        // 如果客户上送了系统标志，但是未找到加解密配置
        if (StringUtils.isEmpty(key)) {
            log.info("special:default key");
            key = encrProps.getAesKey();
        }
        if (StringUtils.isEmpty(iv)) {
            log.info("special:default iv");
            iv = encrProps.getAesIv();
        }

        result.put("key", key);
        result.put("iv", iv);
        return result;
    }


}
